package com.FH.organization.logistics_dispatch;

import com.FH.util.*;
import com.itextpdf.text.DocumentException;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/12/16 0016.
 */
@Stateless
public class LogisticsDispatchDAOImpl extends AccessDB implements LogisticsDispatchDAO {
    /**
     * 查询后勤派单
     *
     * @param search
     * @param page
     * @param size
     */
    @Override
    public ResultDTO getLogisticsDispatchInfo(String search, String page, String size) {

        ResultDTO resultDTO = new ResultDTO();

        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            //先查询数据库中是否存在字段
            String sqlexit = "select count(1) from logistics_dispatch d where 1=1 ";

            String sql_w = "";//查询条件sql组合
            String sql_page = "";//分页组合

            Integer page_ok = Integer.parseInt(page);//将定义page、size的String类型转换成Integer类型
            Integer size_ok = Integer.parseInt(size);

            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size + "";
            }
            if (json.has("logistics_dispatch_id")) {
                sql_w += " AND d.logistics_dispatch_id ='" + json.getString("logistics_dispatch_id") + "'";
            }
            if (json.has("report_torepair_id")) {
                sql_w += " AND d.report_torepair_id ='" + json.getString("report_torepair_id") + "'";
            }
            if (json.has("member_id")) {
                sql_w += " AND d.member_id ='" + json.getString("member_id") + "'";
            }
            if (json.has("dispatch_type")) {
                sql_w += " AND d.dispatch_type ='" + json.getString("dispatch_type") + "'";
            }
            if (json.has("dispatch_status")) {
                sql_w += " AND d.dispatch_status ='" + json.getString("dispatch_status") + "'";
            }
            if (json.has("create_time")) {
                sql_w += " AND d.create_time ='" + json.getString("create_time") + "'";
            }
            if (json.has("update_time")) {
                sql_w += " AND d.update_time ='" + json.getString("update_time") + "'";
            }

            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<LogisticsDispatchShowDTO> result = new ArrayList<LogisticsDispatchShowDTO>();

            if (!existName.equals("0")) {
                String sql = "SELECT d.logistics_dispatch_id,d.member_id,m.member_name,d.logistical_person,d.dispatch_type,d.dispatch_status," +
                        "d.create_time,d.update_time,d.dispatch_desc,d.report_torepair_id FROM logistics_dispatch d LEFT OUTER JOIN kam_member m ON " +
                        "d.member_id = m.member_id WHERE 1=1 " + sql_w + " ORDER BY d.create_time DESC" + sql_page;

                seresult = this.getReportingTo(sql);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++) {

                    LogisticsDispatchShowDTO logisticsDispatchShowDTO = new LogisticsDispatchShowDTO();
                    logisticsDispatchShowDTO.setLogistics_dispatch_id(seresult.get(i)[1]);
                    logisticsDispatchShowDTO.setMember_id(seresult.get(i)[2]);
                    logisticsDispatchShowDTO.setMember_name(seresult.get(i)[3]);
                    logisticsDispatchShowDTO.setLogistical_person(seresult.get(i)[4]);
                    logisticsDispatchShowDTO.setDispatch_type(seresult.get(i)[5]);
                    logisticsDispatchShowDTO.setDispatch_status(seresult.get(i)[6]);
                    logisticsDispatchShowDTO.setCreate_time(seresult.get(i)[7]);
                    logisticsDispatchShowDTO.setUpdate_time(seresult.get(i)[8]);
                    logisticsDispatchShowDTO.setDispatch_desc(seresult.get(i)[9]);
                    logisticsDispatchShowDTO.setReport_torepair_id(seresult.get(i)[10]);

                    result.add(logisticsDispatchShowDTO);
                }


            }
            if (result.size() != 0) {
                resultDTO.setStr(result.size() + "");
                resultDTO.setValues(result);
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resultDTO;
    }

    /**
     * 添加后勤派单
     *
     * @param logisticsDispatchPullDTO
     */
    @Override
    public ResultDTO addLogisticsDispatchInfo(LogisticsDispatchPullDTO logisticsDispatchPullDTO) {

        ResultDTO resultDTO = new ResultDTO();//构建返回对象

        //如果存在则先删除再重新添加
        if(null!=logisticsDispatchPullDTO.getReport_torepair_id()&&!"".equals(logisticsDispatchPullDTO.getReport_torepair_id())){
            String exist = "DELETE FROM logistics_dispatch WHERE report_torepair_id = '"+logisticsDispatchPullDTO.getReport_torepair_id()+"'";
            addReportingTo(exist);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = simpleDateFormat.format(new Date());
        int result = 0;
        if(logisticsDispatchPullDTO.getLogistical_person().length>0){
            for(int i=0;i<logisticsDispatchPullDTO.getLogistical_person().length;i++){
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                String insert = "INSERT INTO logistics_dispatch (logistics_dispatch_id,member_id,logistical_person,dispatch_type," +
                        "dispatch_status,create_time,update_time,dispatch_desc,report_torepair_id) VALUES ('" + uuid + "','" + logisticsDispatchPullDTO.getMember_id()+ "','"
                        + logisticsDispatchPullDTO.getLogistical_person()[i]+ "','"+ logisticsDispatchPullDTO.getDispatch_type()+ "','"+ logisticsDispatchPullDTO.getDispatch_status()+ "','"
                        + date+ "','"+ date+ "','"+ logisticsDispatchPullDTO.getDispatch_desc()+"','"+ logisticsDispatchPullDTO.getReport_torepair_id()+"')";

                result += this.addReportingTo(insert);
            }
        }else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }

        // 判断SQl是否执行成功
        if (result == logisticsDispatchPullDTO.getLogistical_person().length) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;
    }

    /**
     * 修改后勤派单
     *
     * @param logisticsDispatchPullDTO
     */
    @Override
    public ResultDTO updateLogisticsDispatchInfo(LogisticsDispatchPullDTO logisticsDispatchPullDTO) {

        ResultDTO resultDTO = new ResultDTO();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = simpleDateFormat.format(new Date());

        String update = "UPDATE logistics_dispatch SET update_time = '"+date+"'";

        if(null!=logisticsDispatchPullDTO.getLogistical_person()&&!"".equals(logisticsDispatchPullDTO.getLogistical_person())){
            String persons = "";
            if(logisticsDispatchPullDTO.getLogistical_person().length>1){
                for(int i=0;i<logisticsDispatchPullDTO.getLogistical_person().length;i++){
                    if(i!=logisticsDispatchPullDTO.getLogistical_person().length-1){
                        persons += logisticsDispatchPullDTO.getLogistical_person()[i]+",";
                    }else {
                        persons += logisticsDispatchPullDTO.getLogistical_person()[i];
                    }
                }
            }else if(logisticsDispatchPullDTO.getLogistical_person().length==1){
                persons += logisticsDispatchPullDTO.getLogistical_person()[0];
            }
            update += ",logistical_person = '"+persons+"'";
        }
        if(null!=logisticsDispatchPullDTO.getDispatch_type()&&!"".equals(logisticsDispatchPullDTO.getDispatch_type())){
            update += ",dispatch_type = '"+logisticsDispatchPullDTO.getDispatch_type()+"'";
        }
        if(null!=logisticsDispatchPullDTO.getDispatch_status()&&!"".equals(logisticsDispatchPullDTO.getDispatch_status())){
            update += ",dispatch_status = '"+logisticsDispatchPullDTO.getDispatch_status()+"'";
        }
        if(null!=logisticsDispatchPullDTO.getDispatch_desc()&&!"".equals(logisticsDispatchPullDTO.getDispatch_desc())){
            update += ",dispatch_desc = '"+logisticsDispatchPullDTO.getDispatch_desc()+"'";
        }
        update += " WHERE logistics_dispatch_id = '"+logisticsDispatchPullDTO.getLogistics_dispatch_id()+"'";

        int result = this.addReportingTo(update);
        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(logisticsDispatchPullDTO.getLogistics_dispatch_id());
            resultDTO.setStatus("90000");//
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");//
            resultDTO.setDescritpion(warnSrc.update_fail);
        }
        return resultDTO;
    }

    /**
     * 后勤派单导出
     *
     * @param condition
     */
    @Override
    public ResultDTO exportLogisticsDispatch(String condition) {

        ResultDTO resultDTO = new ResultDTO();

        String downloadUrl = "";
        String pdfDownLoadUrl = "";

        List<String[]> seresult = new ArrayList<String[]>();

        List<ExportDispatchShowDTO> result = new ArrayList<ExportDispatchShowDTO>();
        try {
            JSONObject json = new JSONObject(condition);

            String sql_w = "";//查询条件sql组合

            if (json.has("logistics_dispatch_id")) {
                sql_w += " AND d.logistics_dispatch_id ='" + json.getString("logistics_dispatch_id") + "'";
            }
            if (json.has("report_torepair_id")) {
                sql_w += " AND d.report_torepair_id ='" + json.getString("report_torepair_id") + "'";
            }
            if (json.has("member_id")) {
                sql_w += " AND d.member_id ='" + json.getString("member_id") + "'";
            }
            if (json.has("dispatch_type")) {
                sql_w += " AND d.dispatch_type ='" + json.getString("dispatch_type") + "'";
            }
            if (json.has("dispatch_status")) {
                sql_w += " AND d.dispatch_status ='" + json.getString("dispatch_status") + "'";
            }
            if (json.has("create_time")) {
                sql_w += " AND d.create_time ='" + json.getString("create_time") + "'";
            }
            if (json.has("update_time")) {
                sql_w += " AND d.update_time ='" + json.getString("update_time") + "'";
            }

            String sql = "SELECT m.member_name,d.logistical_person,d.dispatch_type,d.dispatch_status," +
                    "d.create_time,d.update_time,d.dispatch_desc FROM logistics_dispatch d LEFT OUTER JOIN kam_member m ON " +
                    "d.member_id = m.member_id WHERE 1=1 " + sql_w + " ORDER BY d.create_time DESC";

            seresult = this.getReportingTo(sql);

            //构建返回对象
            for (int i = 0; i < seresult.size(); i++) {

                ExportDispatchShowDTO exportDispatchShowDTO = new ExportDispatchShowDTO();
                exportDispatchShowDTO.setMember_name(seresult.get(i)[1]);
                exportDispatchShowDTO.setLogistical_person(seresult.get(i)[2]);
                exportDispatchShowDTO.setDispatch_type(seresult.get(i)[3]);
                exportDispatchShowDTO.setDispatch_status(seresult.get(i)[4]);
                exportDispatchShowDTO.setCreate_time(seresult.get(i)[5]);
                exportDispatchShowDTO.setUpdate_time(seresult.get(i)[6]);
                exportDispatchShowDTO.setDispatch_desc(seresult.get(i)[7]);

                result.add(exportDispatchShowDTO);
            }

            String[] headers = {"派单人", "后勤人员", "派单类型", "状态", "派单时间", "完成时间", "备注"};
            String title = "后勤派单";
            String filename = "后勤派单表";

            ExportExcel<ExportDispatchShowDTO> exportExcel = new ExportExcel<ExportDispatchShowDTO>();
            downloadUrl = exportExcel.createExcelFile(exportExcel, title, headers, result, filename);

            try {
                pdfDownLoadUrl = ExportPDF.createPDFFile(seresult, title, headers, filename);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(null != downloadUrl && "" != downloadUrl){
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(downloadUrl);
            resultDTO.setStr(pdfDownLoadUrl);
            resultDTO.setValues(result);
        }
        else{
            resultDTO.setStatus("90001");
        }
        return resultDTO;
    }
}
